<?php
namespace app\home\controller;
use think\Controller;
use think\Input;
use think\Db;
use think\Request;
class Weixin extends Common{
    public $client;
    public $wc;
    public function _initialize(){
        parent::_initialize();
        //获取微信配置信息
        $this->wc = db('wx_user')->where('id',1)->find();
    }
    public function test(){
        echo "<pre>";
        var_dump( $this->wc);
    }
    public function index(){
        define("TOKEN", $this->wc['w_token']);
        $this->valid();
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }

    }
    public function checkSignature()
    {
        if($this->wc['wait_access'] == 0) {
            // you must define TOKEN by yourself
            if (!defined("TOKEN")) {
                throw new Exception('TOKEN is not defined!');
            }
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = TOKEN;
            $tmpArr = array($token, $timestamp, $nonce);
            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                ob_clean();
                echo $_GET['echostr'];
                exit;
            } else {
                return false;
            }
        }else{
            $this->responseMsg();
        }
    }
    public function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (empty($postStr)){
            exit("");
        }
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        //点击菜单拉取消息时的事件推送
        /*
         * 1、click：点击推事件
         * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
         * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
         */
        if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK'){
            $keyword = trim($postObj->EventKey);
        }
        if(empty($keyword)){
            // 关注回复
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                    </xml>";
            $contentStr = $this->wc['concern'];
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
            exit($resultStr);
        }
        // 图文回复
        $wx_img = db('wx_img')->where("keyword like '%$keyword%'")->find();
        if($wx_img) {
            $textTpl = "<xml>
                              <ToUserName><![CDATA[%s]]></ToUserName>
                              <FromUserName><![CDATA[%s]]></FromUserName>
                              <CreateTime>%s</CreateTime>
                              <MsgType><![CDATA[%s]]></MsgType>
                              <ArticleCount><![CDATA[%s]]></ArticleCount>
                              <Articles>
                                  <item>
                                    <Title><![CDATA[%s]]></Title> 
                                    <Description><![CDATA[%s]]></Description>
                                    <PicUrl><![CDATA[%s]]></PicUrl>
                                    <Url><![CDATA[%s]]></Url>
                                  </item>                               
                              </Articles>
                         </xml>";
            if(substr($wx_img['pic'],0,4)=='http'){
                $imgUrl = $wx_img['pic'];
            }else{
                $imgUrl = 'http://'.$_SERVER['HTTP_HOST'].'/public'.$wx_img['pic'];
            }
            $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,'news','1',$wx_img['title'],$wx_img['desc'], $imgUrl, $wx_img['url']);
            exit($resultStr);
        }


        // 文本回复
        $wx_text = db('wx_text')->where("keyword like '%$keyword%'")->find();
        if($wx_text) {
            $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                        </xml>";
            $contentStr = $wx_text['text'];
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
            exit($resultStr);
        }
        // 默认回复
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                    </xml>";
        $contentStr = $this->wc['default'];
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
        exit($resultStr);
    }


//网页授权
    //第一步：用户同意授权，获取code
    function accept(){
        //这个链接是获取code的链接 链接会带上code参数
        //$REDIRECT_URI =url('getCode');"http://".$_SERVER['HTTP_HOST'];
        $REDIRECT_URI="http://".$_SERVER['HTTP_HOST'].'/index.php/home/Weixin/getCode';
        $REDIRECT_URI = urlencode($REDIRECT_URI);
        echo $REDIRECT_URI."<br>";
        $scope = "snsapi_userinfo";
        echo $scope."<br>";
        $state = md5(mktime());
        echo $state."<br>";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->wc['appid']."&redirect_uri=".$REDIRECT_URI."&response_type=code&scope=".$scope."&state="."STATE"."#wechat_redirect";
       // header("location:$url");
    $this->redirect($url);
    }
    //用户同意之后就获取code  通过获取code可以获取一切东西了  机智如我
    function getCode(){
        //获取accse_token
        $code = $_GET["code"];
        //用code获取access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->wc['appid']."&secret=".$this->wc['appsecret']."&code=".$code."&grant_type=authorization_code";
        //这里可以获取全部的东西  access_token openid scope
        $res = $this->https_request($url);
        $res  = json_decode($res,true);
        $openid = $res["openid"];
    $info=Db::table('clt_users')->where('openid',$openid)->find();
        if($info){
            session('userinfo',$info);
        }else{
        echo "<pre>";
        $access_token = $res["access_token"];
        //echo $access_token;
        //这里是获取用户信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        $res = json_decode($res,true);
        $data['openid']=$res['openid'];
        $data['unionid']=$res['unionid'];
        $data['head_pic']=$res['headimgurl'];
        $data['city']=$res['unionid'];
        $data['nickname']=utf8_encode($res['nickname']);
        $data['sex']=$res['sex'];
        $data['reg_time']=time();
        $tag=Db::table(config('database.prefix').'users')->insertGetId($data);
        if($tag){
        $data['user_id']=$tag;
            session('userinfo',$data);
        }else{
            $this->error('出错了，请重试');
        }
}
       $this->redirect('Index/index');
    }

    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}